<?php

namespace app\api\home;

// workerman的操作系列
use app\common\controller\Common;
use Workerman\Worker;

class Workertest extends Common{
    // 设置一个全局变量
    private $worker;
    public function index()
    {
        $this->worker = new Worker("websocket://0.0.0.0:2345");
        // 启动1个进程对外提供服务
        $this->worker->count = 5;
        $this->worker->uidConnections = array();
        // 接收到浏览器发送的数据时回复hello world给浏览器,$data 是传送过来的数据
        $this->worker->onMessage = function ($connection, $data) {
            // $data将会用json格式发送过来
            $data = json_decode($data, false);
            switch ($data->type) {
                case 'login':
                    // 保存该用户的输送数据
                    $connection->uid = $data->uid;
                    dump($connection->uid);
                    $this->worker->uidConnections[$connection->uid] = $connection;
                    break;
                case 'sendMessage':
                    // 发送所有消息
                    $this->send_all($data->message);
                    break;
                case 'sendUser' :
                    // 发送所有消息
                    $this->send_uid($data->to, $data->message);
                    break;
            }
        };
        Worker::runAll();
    }


    public function send_uid($uid, $message)
    {
        $this->worker;
        if (isset($this->worker->uidConnections[$uid])) {
            // 获取之前用户的链接
            $conn = $this->worker->uidConnections[$uid];
            $conn->send($message);
        }
    }

    public function send_all($message)
    {
        foreach ($this->worker->uidConnections as $conn) {
            $conn->send($message);
        }
    }

}
